import { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import leaseStore from '@/stores/LeaseStore';
import Navbar from '@/components/Navbar';
import { View } from '@tarojs/components';
import ButtonComp from '@/components/Button';
import authenticateStore from '@/stores/AuthStore';
import { LeaseEntity } from '@/entities/LeaseEntity';
import { makePhoneCall, navigateTo, showToast } from '@tarojs/taro';
import systemStore from '@/stores/SystemStore';
import useTenant from '@/hooks/useTenant';
import useReport from '@/hooks/useReport';
import userStore from '@/stores/UserStore';
import reportStore from '@/stores/ReportStore';
import BusinessConstant from '@/constant/BusinessConstant';
import HouseLeaseBusiness from '@/business/HouseLeaseBusiness';
import AlterComp from '@/components/Alter';
import HouseCard from '@/components/HouseCard';
import EmptyComp from '@/components/Empty';
import { eventCenter } from '@tarojs/runtime';
import EventConstant from '@/constant/EventConstant';

const TenantHomeComp = () => {
  const {getTenantLeaseHouse} = useTenant();
  const {getReportByTenantId} = useReport();
  const {leaseHouseList, setCurrentLeaseHouse} = leaseStore;
  const {isLogin} = authenticateStore;
  const {user, setCurrentLandlord} = userStore;
  const {tenantReportList} = reportStore;

  const [leaseId, setLeaseId] = useState(0);
  const [refundAlterVisible, setRefundAlterVisible] = useState(false);

  useEffect(() => {
    // 获取租客租赁的房屋
    eventCenter.on(EventConstant.GET_TENANT_LEASE_HOUSE, () => {
      getTenantLeaseHouse(userStore.user?.id);
    });
    // 获取租客全部房屋的维修信息
    eventCenter.on(EventConstant.GET_TENANT_REPORT, () => {
      getReportByTenantId(userStore.user?.id);
    });
  }, []);

  useEffect(() => {
    if (user?.id) {
      // 获取租客租赁的房屋
      getTenantLeaseHouse();
      // 获取租客全部房屋的维修信息
      getReportByTenantId(user.id);
    }
  }, [user?.id]);

  /**
   * 去看租赁房屋
   * @param leaseHouse 租赁房屋信息
   * @param reportStatus 房屋的维修状态（false为待维修，否则为true）
   */
  const toLookLease = (leaseHouse: LeaseEntity.IHouseLease, reportStatus: boolean) => {
    setCurrentLandlord({
      id: leaseHouse.landlordId,
      name: leaseHouse.landlordName,
      headImg: leaseHouse.landlordImg,
      phone: leaseHouse.landlordPhone
    });
    setCurrentLeaseHouse(leaseHouse);
    navigateTo({url: `/pages/tenantLookLeaseHouse/index?reportStatus=${ reportStatus }`});
  };

  /**
   * 获取报修条目的状态：待维修为false，否则为true
   */
  const getReportStatus = (houseId: number) => {
    // 过滤是该房屋并且状态为未维修的条目，若存在则说明该房屋待维修
    const reportHouseList = tenantReportList?.filter(t => t.houseId === houseId && t.status === BusinessConstant.REPORT_PENDING);
    if (reportHouseList?.length !== 0) {
      return false;
    } else {
      return true;
    }
  };

  /**
   * 去报修
   * @param houseId 房屋id
   * @param landlordId 房东id
   */
  const toReport = (houseId: number, landlordId: number) => {
    if (!getReportStatus(houseId)) return;
    navigateTo({url: `/pages/report/index?houseId=${ houseId }&landlordId=${ landlordId }`});
  };

  /**
   * 显示退租提示框
   * @param leaseId
   */
  const showRefundAlter = (leaseId: number) => {
    setLeaseId(leaseId);
    setRefundAlterVisible(true);
  };

  /**
   * 确认退租
   */
  const confirmRefund = async () => {
    // 退租
    await HouseLeaseBusiness.tenantRefund(leaseId);
    // 更新租客已经租赁的房屋
    getTenantLeaseHouse();
    setRefundAlterVisible(false);
    showToast({
      title: '退租成功！',
      icon: 'success'
    });
  };

  return (
    <Navbar
      mode='home'
      title='已租赁房屋'
      bgColor='var(--mini-first)'
    >
      <View className='tenant-home-container' style={ {height: systemStore.haveNavbarHaveTabbarHeight} }>
        {
          leaseHouseList?.length && isLogin ?
            leaseHouseList.map((item: LeaseEntity.IHouseLease, idx: number) => {
                // 获取当前房屋的维修状态
                const houseReportStatus = getReportStatus(item.houseId);
                return (
                  <>
                    <HouseCard
                      key={ idx }
                      houseName={ item.houseName }
                      landlordImg={ item.landlordImg }
                      landlordName={ item.landlordName }
                      toLookHouse={ () => toLookLease(item, houseReportStatus) }
                      houseImg={ JSON.parse(item.houseImg)[0] }
                      statusText={ houseReportStatus ? '正常' : '维修中' }
                      statusBg={ houseReportStatus ? 'var(--mini-first)' : 'var(--mini-fifth)' }
                      housePrice={ item.price }
                      date={ item.updatedAt }
                      dateText='租赁时间：'
                      address={ `${ item.provinceName }${ item.cityName }${ item.areaName }${ item.addressName }` }
                      isFooterSlot={ true }
                      FooterSlotComponent={
                        <View className='btn-group'>
                          <ButtonComp
                            title='联系房东'
                            bgColor='var(--mini-third)'
                            onClick={ () => makePhoneCall({phoneNumber: item.landlordPhone}) }
                          />
                          <ButtonComp
                            title={ houseReportStatus ? '房间报修' : '已报修' }
                            bgColor={ houseReportStatus ? 'var(--mini-first)' : 'var(--bg-fourth)' }
                            onClick={ () => toReport(item.houseId, item.landlordId) }
                          />
                          <ButtonComp
                            title='退租'
                            bgColor='var(--mini-fifth)'
                            onClick={ () => showRefundAlter(item.leaseId) }
                          />
                        </View>
                      }
                    />
                  </>
                );
              }
            ) : <EmptyComp text={ isLogin ? '暂无租赁房屋，去房屋市场看看吧！' : '请登陆后查看' }/>
        }
      </View>
      <AlterComp
        visible={ refundAlterVisible }
        onClose={ () => setRefundAlterVisible(false) }
        onConfirm={ confirmRefund }
        content='您确定要退租吗？'
      />
    </Navbar>
  );
};

export default observer(TenantHomeComp);
